import React, {FC, useEffect, useRef, useState} from "react";
import {Button, Input, message, Select, Drawer, Table, DatePicker, Tag, Descriptions,Image} from "antd";
import {getOriginString, getSecretString} from "@/utils/encrypt";
import {useRequest} from "@umijs/hooks";
import {fetchRequest} from "@/utils/Request";
import {url} from "@/utils/url";
import {RangeValue} from "rc-picker/lib/interface";
import './index.css'
import {EyeOutlined, RiseOutlined, SearchOutlined} from "@ant-design/icons";
import exportExcel from "@/utils/exportExcel";
import getImgInfo from "@/utils/getImgInfo";


const {Option} = Select
const {RangePicker} = DatePicker

const optionList = [
    {
        title: '全部',
        value: ''

    },
    {
        title: '待审核',
        value: '0'
    },
    {
        title: '审核通过',
        value: '1'
    },
    {
        title: '审核不通过',
        value: '2'
    },
]
const list = [{color: '#722ed1', text: '待审核', key: 0}, {color: '#108ee9', text: '审核通过', key: 1}, {
    color: '#f50',
    text: '审核不通过',
    key: 2
}]
let infoKey = [
    {
        key: 'visitorName',
        title: '访客姓名'
    },
    {
        key: 'visitorPhone',
        title: '访客电话',
        render: (phone: string) => <>{getOriginString(phone)}</>
    },
    {
        title: '学校校区名称',
        key: 'collegeAndAreaName',
    },
    {
        key: 'visitorCount',
        title: '访客人数'
    },
    {
        key: 'idNumber',
        title: '身份证号',
        render: (phone: string) => <>{getOriginString(phone)}</>
    },
    {
        title: '访客时间',
        render: (item: any) => <>{item.startTime}~{item.endTime}</>
    },
    {
        title: '创建时间',
        key: 'createTime',
        className: 'createTime'
    },
    {
        title: '开始时间',
        key: 'startTime',
        dataIndex: 'startTime',
    },
    {
        title: '结束时间',
        key: 'endTime',
        dataIndex: 'endTime',
    },
    {
        title: '教师姓名',
        key: 'teacherName',
    },
    {
        title: '教师电话',
        key: 'teacherPhone',
        render: (phone: string) => <>{getOriginString(phone)}</>
    },
    {
        title: '审核状态',
        key: 'auditState',
        dataIndex: 'auditState',
        render: (auditState: string) => {
            const temState = auditState || 0;
            const item = list.find(item => item.key === temState)
            return <Tag color={item?.color}>{item?.text}</Tag>
        }
    },
    {
        title: '访客事由',
        key: 'reason',
        render: (reason: string) => <div className={'reason'}>{reason}</div>
    },
    {
        title: '附件',
        key: 'storeName',
        render: (photo: string) => <div className={'storeName'}><Image
            src={`${url.GET_PERSON_LEAVE_URL}?accessToken=${getImgInfo(photo)}`}/></div>
    },

]

const infoKeys = [
    {
        key: 'visitorName',
        title: '访客姓名'
    },
    {
        key: 'visitorPhone',
        title: '访客电话',
        render: (phone: string) => <>{getOriginString(phone)}</>
    },
    {
        title: '学校校区名称',
        key: 'collegeAndAreaName',
    },
    {
        key: 'visitorCount',
        title: '访客人数'
    },
    {
        key: 'idNumber',
        title: '身份证号',
        render: (phone: string) => <>{getOriginString(phone)}</>
    },
    {
        title: '访客时间',
        render: (item: any) => <>{item.startTime}~{item.endTime}</>
    },
    {
        title: '创建时间',
        key: 'createTime',
        className: 'createTime'
    },
    {
        title: '开始时间',
        key: 'startTime',
        dataIndex: 'startTime',
    },
    {
        title: '结束时间',
        key: 'endTime',
        dataIndex: 'endTime',
    },
    {
        title: '教师姓名',
        key: 'teacherName',
    },
    {
        title: '教师电话',
        key: 'teacherPhone',
        render: (phone: string) => <>{getOriginString(phone)}</>
    },
    {
        title: '审核状态',
        key: 'auditState',
        dataIndex: 'auditState',
        render: (auditState: string) => {
            const temState = auditState || 0;
            const item = list.find(item => item.key === temState)
            return <Tag color={item?.color}>{item?.text}</Tag>
        }
    },
    {
        title: '访客事由',
        key: 'reason',
        render: (reason: string) => <div className={'reason'}>{reason}</div>
    },
    {
        title: '附件',
        key: 'storeName',
        render: (photo: string) => <div className={'storeName'}><Image
            src={`${url.GET_PERSON_LEAVE_URL}?accessToken=${getImgInfo(photo)}`}/></div>
    },

]

const tablename = [
    {
        title: "设备名称",
        dataIndex: "deviceName",
        key: "deviceName",
        align: "center" as "center"
    },
    {
        title: "设备状态",
        dataIndex: "deviceState",
        key: "deviceState",
        align: "center" as "center"
    }
];
const tempParams = {
    visitorPhone: '',
    auditState: '',
    startDate: '',
    endDate: '',
    collegeId: '',
    teacherName: ''
}


const VisitorSreview = () => {


    const columns = [
        {
            title: '访客姓名',
            key: 'visitorName',
            dataIndex: 'visitorName',
        },
        {
            title: '访客电话',
            key: 'visitorPhone',
            dataIndex: 'visitorPhone',
            render: (phone: string) => <div>{getOriginString(phone)}</div>

        },
        {
            title: '学校校区名称',
            key: 'collegeAndAreaName',
            dataIndex: 'collegeAndAreaName'
        },

        {
            title: '开始时间',
            key: 'startTime',
            dataIndex: 'startTime',
        },
        {
            title: '结束时间',
            key: 'endTime',
            dataIndex: 'endTime',
        },
        {
            title: '创建时间',
            key: 'createTime',
            dataIndex: 'createTime',
        },
        {
            title: '教师姓名',
            key: 'teacherName',
            dataIndex: 'teacherName',
        },
        {
            title: '教师电话',
            key: 'teacherPhone',
            dataIndex: 'teacherPhone',
            render: (phone: string) => <div>{getOriginString(phone)}</div>
        },
        {
            title: '审核状态',
            key: 'auditState',
            dataIndex: 'auditState',
            render: (auditState: string) => {
                const temState = auditState || 0;
                const item = list.find(item => item.key === temState)
                return <Tag color={item?.color}>{item?.text}</Tag>
            }
        },
        {
            title: '操作',
            render: (item: any) => <Tag color={'#108ee9'} icon={<EyeOutlined/>} className='executed'
                                        onClick={() => getVisitor({id: item.id})}>查看</Tag>
        }
    ]


    const [visible, setVisible] = useState(false);
    const [info, setInfo] = useState<any>({});
    const params = useRef({
        collegeId: '',
        endDate: '',
        startDate: '',
        auditState: '',
        visitorPhone: '',
        isAuditVisitor:1,
    })
    const {
        tableProps,
        run,
    } = useRequest(((current, params) => fetchRequest(url.GET_TABLE_VISITOR, {
        pageSize: current.pageSize,
        pageStart: current.current,
        ...params

    })), {
        paginated: true,
        manual: true,
        formatResult: (response: any) => {
            return {
                list: response.data?.rows,
                total: response.data?.total,
                success: response.success,
                errorMsg: response.errorMsg
            };
        }
    })
    //导出
    const {run: runs, data} = useRequest((params) => fetchRequest(url.GET_VISITOR_EXPORT, params), {
        manual: true,
        onSuccess: async (result, params) => {
            if (result.success) {
                const tempKeys = {}
                infoKey.map((keyItem) => {
                    if (keyItem.key) {
                        tempKeys[keyItem.key] = keyItem.title
                    }
                })
                const data = result.data.map((item: any) => {
                    const tempItem = {}
                    Object.keys(tempKeys).map(keyItem => {
                        if(tempKeys[keyItem] == '附件'){
                            return
                        }
                        tempItem[tempKeys[keyItem]] = item[keyItem]
                    })
                    tempItem['教师电话'] = getOriginString(item.teacherPhone)
                    tempItem['访客电话'] = getOriginString(item.visitorPhone)
                    tempItem['身份证号'] = getOriginString(item?.idNumber)
                    tempItem['审核状态'] = list.find(listItem => listItem.key === item?.auditState)?.text

                    return tempItem
                })
                exportExcel(data, '访客审核记录表.xlsx')
            } else {

                message.error(result.errorMsg)

            }
        }
    })


    const selectClick = async () => {
        params.current = {
            ...tempParams,isAuditVisitor:1
        }


        if (tempParams.visitorPhone) {

            params.current.visitorPhone = getSecretString(tempParams.visitorPhone)
        }

        const data = await run({pageSize: 10, current: 1}, params.current)

        if (!data.success) {
            message.error(data.errorMsg)
        }
    }
    const stateChange = (value: string) => {
        tempParams.auditState = value

    }

    const timerChange = (date: any, dateString: any) => {
        tempParams.startDate = dateString[0]
        tempParams.endDate = dateString[1]
    }

    const getVisitor = async (params: any) => {

        const {data, success} = await fetchRequest(url.GET_VISITOR, params)
        if (success) {
            infoKey = [...infoKeys]
            setInfo(data)
            setVisible(true)
        }
    }


    const importClick = async () => {
        params.current = {
            ...tempParams,isAuditVisitor:1
        }


        if (tempParams.visitorPhone) {

            params.current.visitorPhone = getSecretString(tempParams.visitorPhone)
        }

        await runs({...params.current})

    }

    useEffect(() => {
        (async () => {
                Object.keys(tempParams).map(item => tempParams[item] = '')
                await selectClick()
            }
        )()
    }, [])
    const getShow = () =>{
        infoKey = []
        setVisible(false)
    }

    /*render*/
    const search = () => (<div className={'search'}>

        <div className={'search-item'}>
            <div className={'title'}>访客电话号码:</div>
            <div><Input placeholder={'请输入访客电话'} onInput={(e) => tempParams.visitorPhone = e.currentTarget.value}/>
            </div>
        </div>
        <div className={'search-item'}>
            <div className={'title'}>教师姓名:</div>
            <div><Input placeholder={'请输入教师姓名'} onInput={(e) => tempParams.teacherName = e.currentTarget.value}/>
            </div>
        </div>

        <div className={'search-item'}>
            <div className={'title'}>请选择时间:</div>
            <div><RangePicker onChange={timerChange}/></div>
        </div>
        <div className={'search-item'}>
            <div className={'title'}>请选择状态:</div>
            <div>
                <Select defaultValue={optionList[0].title} onChange={stateChange}>
                    {optionList.map((item, index) => <Option key={index}
                                                             value={item.value}>{item.title}</Option>)}</Select>
            </div>
        </div>
        <div className={'btn'}>
            <Button type={'primary'} onClick={selectClick} icon={<SearchOutlined/>}>查询</Button>
            <Button type={'primary'} onClick={importClick} icon={<RiseOutlined/>}>导出</Button>
        </div>


    </div>)

    const table = () => <>
        <Table className={'table-form'} columns={columns} rowKey="id"     {...tableProps as any} />
    </>

    const drawer = () => <>
        <Drawer title="访客详情"
                placement="right"
                closable={false}
                onClose={() => getShow()}
                visible={visible}
                width={1200}
        >
            <Descriptions bordered>
                {infoKey.map((item: any, index) =>
                    <Descriptions.Item className={item.className} label={item.title}
                                       key={index}>{item.render ? item.render(item.key ? info[item.key] : info) : info[item.key]}</Descriptions.Item>)}
            </Descriptions>
            {info.auditState === 1 ?<div>
                <Table columns={tablename} dataSource={info.deviceList}  rowKey={(record: any) => record.deviceName}/>
            </div>:null}
        </Drawer>
    </>
    return <div className={'wrap bulk'}>
        {search()}
        {table()}
        {drawer()}
    </div>
}

export default VisitorSreview
